package com.eds.mall.search.config;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.eds.common.exception.RRException;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.client.HttpAsyncResponseConsumerFactory;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

/**
 * @author zz_code
 * @data 2024/5/4 13:01
 */
@Configuration
@Slf4j
public class ElasticSearchConfigtion {

    @Value("#{'${elastic.search.http}'.split(',')}")
    List<String> httpList;

    public static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();
       /* builder.addHeader("Authorization", "Bearer " + TOKEN);
        builder.setHttpAsyncResponseConsumerFactory(
                new HttpAsyncResponseConsumerFactory
                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024 * 1024));*/
        COMMON_OPTIONS = builder.build();
    }

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        if (CollectionUtils.isEmpty(httpList)){
            new RRException("ES 启动失败，未配置Client地址");
        }

        HttpHost[] hosts = httpList.stream().map(obj -> {
            String[] split = obj.split(":");
            int port = -1; // port =-1 说明没有端口号
            if(split.length > 1) port = Integer.valueOf(split[1].trim());
            HttpHost httpHost = new HttpHost(split[0].trim(), port,"http");
            return httpHost;
        }).toArray(HttpHost[]::new);

        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(hosts));

        Arrays.asList(hosts).forEach(obj -> {
            log.info("ES Client尝试连接路径：{}",obj.toString());
        });

        return client;
    }
}
